package com.hiwan.system.web.role;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hiwan.platform.utils.StringUtils;
import com.hiwan.system.common.base.BaseController;
import com.hiwan.system.pojo.RoleInfo;
import com.hiwan.system.pojo.RoleMenuInfo;
import com.hiwan.system.pojo.TreeNode;
import com.hiwan.system.pojo.UserRelation;
import com.hiwan.system.service.role.RoleService;
import com.hiwan.system.service.user.UserService;
import com.hiwan.system.util.UserCacheUtils;

import net.sf.json.JSONArray;

@Controller
@RequestMapping("/role")
public class RoleController extends BaseController{
	
	@Autowired
	private RoleService roleService;
	@Autowired
	private UserService userService;
	
	/**
	 * 跳转到查询页面
	 * @return
	 */
	@RequestMapping("toQuery.do")
	public String toQuery(ModelMap model) {
		return "role/query";
	}

	
	@RequestMapping("list")
	public String getRoleDetailList(ModelMap model) {
		List<RoleInfo> roleList = UserCacheUtils.getRoleList();
		model.put("roleList", roleList);
		return "role/roleList";
	}

	/**
	 * 跳转至新增页面
	 */
	@RequestMapping("toInsert")
	public String toInsert(ModelMap model) {
		model.put("roleInfo", new RoleInfo());
		return "role/roleDetail";
	}

	/**
	 * 获取角色详细信息
	 */
	@RequestMapping(value="getRoleDetailInfo/{roleId}",method=RequestMethod.GET)
	public String getRoleDetailInfo(@PathVariable("roleId") String roleId, ModelMap model) {
		RoleInfo roleInfo = roleService.get(roleId);
		model.put("roleInfo", roleInfo);
		model.put("operFlag", "detail");
		return "role/roleDetail";
	}
	
	/**
	 * 保存角色对应菜单
	 */
	@RequestMapping("saveRoleMenu")
	public @ResponseBody String saveRoleMenu(RoleInfo roleInfo, RoleMenuInfo roleMenuInfo) {
		String data="";
		int result = this.roleService.saveRoleMenu(roleInfo, roleMenuInfo);
		if (result == 1) {
			// 下面代码有待商榷
			/*int temp = this.userService.updateUserMenuByRoleInfo(roleInfo);
			if (temp == 0) {// 0--成功，1--失败
				//result = 2;
				data = "{\"status\":\"ok\",\"message\":\"保存成功\"}";
			}else{
				data = "{\"status\":\"fail\",\"message\":\"更新角色对应菜单失败\"}";
			}*/
			data = "{\"status\":\"ok\",\"message\":\"保存成功\"}";
		}else{
			data = "{\"status\":\"fail\",\"message\":\"保存失败\"}";
		}
		return data;
	}
	
	// 保存用户角色对应菜单
	/**
	 * 保存用户
	 */
	public @ResponseBody String saveUserRoleMenu(){
		return null;
	}
	

	/**
	 * 新增角色
	 */
	@RequestMapping(value="insert",method=RequestMethod.POST)
	@ResponseBody
	public String[] insert(RoleInfo roleInfo, HttpSession session) {
		int result = this.roleService.add(roleInfo);
		if (result == 1) return new String[]{"ok","保存成功"};
		if(result == 2) return new String[]{"fail","已存在同名角色,请修改角色名称！"};
		return new String[]{"fail","保存失败！"};
	}

	/**
	 * 修改角色信息
	 */
	@RequestMapping(value="update",method=RequestMethod.POST)
	public @ResponseBody String[] update(RoleInfo roleInfo, HttpSession session) {
		int result = this.roleService.modify(roleInfo);
		if (result == 1) return new String[]{"ok","修改成功"};
		if(result == 2) return new String[]{"fail","已存在同名角色,请修改角色名称！"};
		return new String[]{"fail","修改失败！"};
	}
	
    /**
     * fuel ux tree插件的数据源，一级菜单、二级菜单</p>
     * @param parentId
     * @return
     *//*
    @RequestMapping("/getRoleMenu.do")
    public @ResponseBody Map<String, TreeNode> getRoleMenu(RoleInfo roleInfo,String parentId, HttpSession session) {
    	List<String> roleMenulist= roleService.getRoleMenuList(roleInfo.getRoleId());
    	
    	List<MenuInfo> children=  menuService.getAllMenuInofList(parentId);
    	
    	
    	Map<String, TreeNode> childrenMap = new HashMap<String, TreeNode>();
    	Map<String, TreeNode> parentMap = new HashMap<String, TreeNode>();
    	
    	if(roleMenulist==null&&children!=null){//新增的角色 ,对应的角色菜单为Null
    		for (MenuInfo child : children){
    			if(child.getParentMenu().equals("0")){
    				parentMap.put(child.getMenuId(), TreeNode.buildTreeNode(child.getMenuId(),null,child.getMenuName(), "org"));
    			}else {
    				childrenMap.put(child.getMenuId(), TreeNode.buildTreeNode(child.getMenuId(),parentId,child.getMenuName(), "org"));
    			}
    		}
    	}else if(roleMenulist!=null&&children!=null){
    		for (int i = 0; i < children.size(); i++) {
    			// 如果是父节点，且id在roleMenuList中
    			String menuId=children.get(i).getMenuId();
    			String menuParentId=children.get(i).getParentMenu();
    			
				if(menuParentId.equals("0")){
					if(roleMenulist.contains(menuId)){
						parentMap.put(menuId, TreeNode.buildTreeNode(menuId,null,children.get(i).getMenuName(), "org","true","false","true"));
					}else{
						parentMap.put(menuId, TreeNode.buildTreeNode(menuId,null,children.get(i).getMenuName(), "org","false","false","true"));
					}
    			}else {
    				if(roleMenulist.contains(menuId)){
    					childrenMap.put(menuId, TreeNode.buildTreeNode(menuId,parentId,children.get(i).getMenuName(), "org","true","false","false"));
    				}else{
    					childrenMap.put(menuId, TreeNode.buildTreeNode(menuId,parentId,children.get(i).getMenuName(), "org","false","false","false"));
    				}	
    			}
			}
    	}
    	
    	
    	
    	//String initMenuMessage = roleService.getInitMenu();
    	//String initRoleMenu = roleService.getInitRoleMenu(roleInfo.getRoleId());
    	
    	if(parentId!=null){//子菜单集合
    		return childrenMap;
    	}else{
    		return parentMap;
    	}
    }
*/
	/**
	 *查询当前角色的菜单权限
	 * @param roleId
	 * @param model
	 * @return
	 */
	@RequestMapping("getRoleMenuDetailInfo")
	public String getRoleMenuDetailInfo(String roleId,ModelMap model) {
		List<TreeNode> nodeList =null;
		if(StringUtils.isNotEmpty(roleId)){
			nodeList = roleService.getRoleMenuNodes(roleId);
		}
		JSONArray jsonArray = JSONArray.fromObject( nodeList ); 
		model.put("roleId", roleId);
		model.put("jsonArray", jsonArray.toString());
		return "role/roleMenu";
	}

	/**
	 * 删除角色
	 */
	@RequestMapping("delete")
	public @ResponseBody String[] delete(RoleInfo roleInfo) {
		int result = this.roleService.remove(roleInfo.getRoleId());
		if (result == 1) return new String[] {"ok", "删除成功！"};
		return new String[] { "fail", "删除失败！" };
	}
	
	/**
	 * 检查角色状态
	 * @return
	 */
	@RequestMapping("checkStatus")
	public @ResponseBody String[] checkStatus(RoleInfo roleInfo){
		RoleInfo role = roleService.get(roleInfo);
		if(StringUtils.equals("1", role.getRoleStatus())){
			return new String[]{"fail","角色为【启用】状态，无法删除！"};
		}
		return new String[]{"ok","可删除！"};
	}
	
	/**
	 * 得到可用的角色
	 * @author lsb
	 * @since  2015-11-13 下午3:05:11
	 * @version hiwan 3.0	
	 * @return
	 */
	@RequestMapping("/listEnableRole.do")
	public @ResponseBody Map<String,Object> toQuetyDetail(HttpSession session,String relationId,String userFlag,ModelMap model){
		HashMap<String,Object> map=new HashMap<String,Object>();
		RoleInfo roleInfo = new RoleInfo();
		String roleId = (String) session.getAttribute("sessionRole");
		roleInfo.setRoleLevel(roleService.get(roleId).getRoleLevel());
		List<RoleInfo> roleList = roleService.getEnableRoleList(roleInfo);
		
		UserRelation ur = userService.selectByUserRelation(relationId);
		List<String> roleIds = ur.getRoleIds();
		List<RoleInfo> chooseRoleList = new ArrayList<RoleInfo>();
		for (int i = 0; i < roleIds.size(); i++) {
			for (int j = 0; j < roleList.size(); j++) {
				if (roleIds.get(i).equals(roleList.get(j).getRoleId())) {
					chooseRoleList.add(roleList.get(j));
					break;
				}
			}
		}
		
		map.put("data", roleList);
		map.put("chooseRoleList",chooseRoleList);
		return map;
	}

}

